package com.sishu.websocket4.common;

//import com.sishu.websocket.po.Users;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.Resource;

@Component
public class WebSocketAPI extends TextWebSocketHandler {

    @Resource
    private MyWebSocketServer myWebSocketServer;



    @Override //该方法会在websocket连接成功后被调用
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {

       String token = getTokenFromSession(session);
        System.out.println("token:"+token);
       //暂时关闭验证
//        if (token == null || token.isEmpty()) {
//            session.sendMessage(new TextMessage("账号用户名密码不正确，请重新登录"));
//            session.close(); // 验证失败，关闭连接
//            return;
//        }
        myWebSocketServer.onOpen(session);
//        Users users = (Users)session.getAttributes().get("user");
        //WebSocketSession是websocket连接对应的会话
        System.out.println("建立连接了");
    }
    @Override //该方法是在websocket收到消息的时候自动调用
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        myWebSocketServer.onMessage(message, session);
    }

    @Override //该方法是在websocket连接出现异常的时候自动调用的
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //exception记录了异常信息
        myWebSocketServer.onError(session,exception);
        System.out.println("连接出现异常了");
    }
    @Override //该方法是在websocket连接关闭后自动调用的
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        //status 为关闭的状态
        System.out.println("连接关闭了");
    }

    private String getTokenFromSession(WebSocketSession session) {
        // 从session中获取 token（这里假设 token 是在 URL 中传递的）
        String uri = session.getUri().toString();
        String token = null;
        if (uri.contains("token=")) {
            token = uri.substring(uri.indexOf("token=") + 6);
        }
        return token;
    }


//    发送给特定客户端

}